<template>
  <div style="padding: 10px;">
    <el-card shadow="never">
      <div class="card-header">
      </div>
      <el-scrollbar>
        <div class="input-section">
          <div >
            <label>{{ $t('message.home.prompt') }}</label>
            <CustomMention v-model="generationStore.params.prompt" :triggerChars="['@', ',','，']"
              :options="state.localOptions" :remote-method="remoteSearch" @select="handleSelect" @clear="handleClear"
              class="custom-mention" />
          </div>
          <div class="input-group">
            <el-tabs v-model="state.activeName">
              <el-tab-pane label="Translate" name="translate">
                <TranslatePanel/>
              </el-tab-pane>
              <el-tab-pane label="TagPanel" name="tag">
                <Tag/>
              </el-tab-pane>
              <el-tab-pane label="Baidu" name="Baidu">
                <BaiduTranslatePanel/>
              </el-tab-pane>
              <el-tab-pane label="Lora" name="Lora">
                <LoraLoader />
              </el-tab-pane>
              <el-tab-pane label="Global" name="Global">
                <el-text>{{ generationStore.combinedPrompt }}</el-text>
              </el-tab-pane>
              <el-tab-pane label="Preset" name="Preset">
              <div class="model-selector">
                <el-select v-model="state.presets" :placeholder="$t('message.home.selectPreset')" @change="handelSelectPreset"
                  size="default" clearable multiple filterable>
                  <el-option v-for="item in state.presetOptions" :key="item.id" :label="item.name" :value="item.tags" />
                </el-select>
                <el-select v-model="state.negative" :placeholder="$t('message.home.selectNegative')" @change="handelSelectNegative"
                  size="default" clearable multiple filterable>
                  <el-option v-for="item in state.negativeOptions" :key="item.id" :label="item.name" :value="item.tags" />
                </el-select>
                <el-button class="refresh-btn" icon="Refresh" v-loading="presetLoading"  plain @click="handleLoadPreset" />
                <el-select v-model="modelStore.currentModel" :placeholder="$t('message.home.selectModel')"
                  @change="(value: string) => modelStore.updateModel(value)" size="default">
                  <el-option v-for="item in modelStore.modelList" :key="item.title" :label="item.title" :value="item.title" />
                </el-select>
                <el-button class="refresh-btn"  v-loading="modelStore.loading" icon="Refresh"  plain
                  @click="modelStore.fetchModels" />
              </div>
              </el-tab-pane>
            </el-tabs>
          </div>

          <div class="input-group">
            <label>{{ $t('message.home.batchPrompt') + "|" }}</label>
            <el-input v-stop-comfy-events v-model="batchPrompt" class="batch-input" type="textarea" resize="none" :rows="3" />
          </div>

          <div class="input-group">
            <label>{{ $t('message.home.negativePrompt') }}</label>
            <el-input v-stop-comfy-events v-model="generationStore.params.negative_prompt" class="negative-input" type="textarea"
              resize="none" :rows="3" />
          </div>
        </div>
      </el-scrollbar>

      <div class="card-footer">
        <div class="action-section">
          <div class="counter">
            <el-icon>
              <Document />
            </el-icon>
            <span>{{ $t('message.home.count') }}: {{ generationStore.params.prompt.length }}</span>
          </div>

          <div class="action-buttons">
            <el-button type="primary" icon="Promotion" :loading="generationStore.isJob"
              @click="generationStore.generateImages" class="generate-btn">
              {{ $t('message.home.generate') }}
            </el-button>

            <el-button type="success" icon="MagicStick" :loading="generationStore.isJob" @click="handleBatchGenerate"
              class="batch-btn">
              {{ $t('message.home.batchGenerate') }}
            </el-button>
          </div>

          <div class="progress-indicator">
            <el-tag type="info" v-if="state.isBatching">
              <el-icon>
                <Loading />
              </el-icon>
              <span>{{ batchProgressText }}</span>
            </el-tag>
            <div class="counter" v-else>
            <el-icon>
              <CircleCheck />
            </el-icon>
            <span>{{ $t('message.home.ready') }}</span>
          </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { characterApi } from '@renderer/api/character';
import { commonApi } from '@renderer/api/common';
import { useGenerationStore } from '@renderer/stores/useGenerationStore';
import { useModelStore } from '@renderer/stores/useModelStore';
import { ElMessage } from 'element-plus';
import { computed, defineAsyncComponent, onMounted, reactive, ref } from 'vue';
import TranslatePanel from '@renderer/views/home/component/TranslatePanel.vue'
import { translateApi } from '@renderer/api/translate';

defineOptions({
  name: 'HomePanel' // 显式定义组件名称
})

interface presetOption {
  customize_name: string
  id: string
  name: string
  tags: string
}


const generationStore = useGenerationStore()
const modelStore = useModelStore()
const Setting = defineAsyncComponent(() => import('./component/Setting.vue'))
const LoraLoader = defineAsyncComponent(() => import('@renderer/views/random/component/LoraLoader.vue'))
const loading = ref(false)
const presetLoading = ref(false)
const batchPrompt = ref('')
const handleClear = () => {
  state.localOptions.splice(0)
}

const handleLoadPreset = async () => {
  presetLoading.value = true;
  try{
     await commonApi().getPromptItemByClassType({class_type:'preset'}).then((res) => {
        if (res.status == 200) {
          state.presetOptions = res.data.data
        }
      })
     await commonApi().getPromptItemByClassType({class_type:'negative'}).then((res)=>{
        state.negativeOptions = res.data.data
      })
  }
  catch{

  }finally{
    presetLoading.value = false
  }
}

const handelSelectPreset = (value: string[]) => {
  if (value.length === 0) {
    generationStore.setPrests('');
    return;
  }

  // 组合标签并设置到 store
  const combinedTags = value.join(',');
  generationStore.setPrests(combinedTags);
}

const handelSelectNegative = (value: string[]) => {
  if (value.length === 0) {
    generationStore.setNegativePrompt('');
    return;
  }
  // 组合标签并设置到 store
  const combinedTags = value.join(',');
  generationStore.setNegativePrompt(combinedTags);
}

const remoteSearch = async (query, prefix) => {
  query = query.replace(/\u00A0/g, ' ');
  if (prefix == '@') {
    characterApi().getCharacterTags({ tag: query, tag_des: query }).then(res => {
      state.localOptions = res.data;
    }).finally(() => {
      loading.value = false;
    });
  }
  else {
    translateApi().getTranslateMention({ query:query }).then(res => {
      state.localOptions = res.data.data;
    }).finally(() => {
      loading.value = false;
    });
  }
}

const handleSelect = (item:any) => {
  state.localOptions.splice(0)
}

const CustomMention = defineAsyncComponent(() => import('./component/MyMention.vue'))
const Tag = defineAsyncComponent(() => import('./component/Tag.vue'))
const BaiduTranslatePanel = defineAsyncComponent(() => import('./component/BaiduTranslatePanel.vue'))

const state = reactive({
  isOpen: false,
  openPath: '',
  outPutPath: [],
  imageList: [],
  viewportHeight: 0,
  scrollTop: 0,
  currentPage: 1,
  pageSize: 10,
  totalImages: 0,
  isLoadingMore: false,
  allImages: [],
  content: '',
  localOptions: [] as [],
  currentBatchIndex: 0,
  totalBatches: 0,
  isBatching: false,
  presets: [] as string[],
  negative: [] as string[],
  presetOptions: [] as presetOption[],
  negativeOptions: [] as presetOption[],
  activeName: 'translate',
})

const handleBatchGenerate = async () => {
  try {
    state.isBatching = true
    generationStore.images.splice(0)
    const batchArray = batchPrompt.value.split("\n").filter(Boolean)

    state.totalBatches = batchArray.length
    state.currentBatchIndex = 0

    for (const [index, item] of batchArray.entries()) {
      state.currentBatchIndex = index + 1
      generationStore.params.prompt = item.trim()

      try {
        await generationStore.generateImages()
      } catch (e) {
        ElMessage.error(`第 ${state.currentBatchIndex} 个提示词生成失败: ${e.message}`)
      }

      // 添加间隔避免请求过快
      await new Promise(r => setTimeout(r, 500))
    }
  } catch (error) {
    ElMessage.error(`批量处理失败: ${error.message}`)
  } finally {
    state.isBatching = false
    state.currentBatchIndex = 0
    state.totalBatches = 0
  }
}

const batchProgressText = computed(() => {
  return state.isBatching
    ? `${state.currentBatchIndex}/${state.totalBatches}`
    : '0/0'
})

onMounted(() => {
  handleLoadPreset()
  modelStore.fetchModels()
})
</script>

<style scoped>

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  font-size: 1.25rem;
  font-weight: 600;
  color: var(--el-text-color-primary);
}

.model-selector {
  display: flex;
  align-items: center;
  gap: 10px;
}

:deep(.el-select) {
  width: 280px;
}

.refresh-btn {
  flex-shrink: 0;
}

.input-section {
  padding: 2px 2px;
}

.input-group {
  margin-bottom: 12px;
}

.input-group:last-child {
  margin-bottom: 0;
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 0.875rem;
  font-weight: 500;
  color: var(--el-text-color-regular);
}

.custom-mention {
  width: 100%;
}

.batch-input,
.negative-input {
  width: 100%;
}

:deep(.el-textarea__inner) {
  border-radius: 10px;
  padding: 12px 16px;
  border: 1px solid var(--el-border-color);
  background: var(--el-fill-color-lighter);
  transition: all 0.3s ease;
  font-family: inherit;
  box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.03);
}

:deep(.el-textarea__inner):hover {
  border-color: var(--el-border-color-hover);
}

:deep(.el-textarea__inner):focus {
  border-color: var(--el-color-primary);
  background: var(--el-bg-color);
  box-shadow: 0 0 0 3px var(--el-color-primary-light-5);
}

.card-footer {
  padding: 16px 24px;
}

.action-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 16px;
}

.counter {
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--el-fill-color);
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 0.875rem;
  color: var(--el-text-color-regular);
}

.counter .el-icon {
  color: var(--el-text-color-secondary);
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.generate-btn,
.batch-btn {
  padding: 10px 24px;
  border-radius: 10px;
  font-weight: 500;
  transition: all 0.2s ease;
}

.generate-btn:hover,
.batch-btn:hover {
  transform: translateY(-2px);
  box-shadow: var(--el-box-shadow-light);
}

.progress-indicator {
  margin-left: auto;
}

.el-tag {
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 8px;
  background: var(--el-fill-color);
  border: none;
  color: var(--el-text-color-regular);
}

.setting-section {
  margin-top: 24px;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: var(--el-box-shadow-light);
  border: 1px solid var(--el-border-color);
}

@media (max-width: 768px) {
  .action-section {
    flex-direction: column;
    align-items: stretch;
  }

  .progress-indicator {
    margin-left: 0;
    margin-top: 8px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .model-selector {
    width: 100%;
  }

  :deep(.el-select) {
    width: 100%;
  }
}
</style>
